//
//  GYXNewFeatureView.swift
//  GYXWeibo
//
//  Created by Twisal on 2017/3/7.
//  Copyright © 2017年 Twisal. All rights reserved.
//

import UIKit

class GYXNewFeatureView: UIView {
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterButton: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!

    /// 创建视图的类方法
    ///
    /// - Returns: 新特性视图
    class func newFeature() -> GYXNewFeatureView {
        let nib = UINib(nibName: "GYXNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: self, options: nil)[0] as! GYXNewFeatureView
        v.frame = UIScreen.main.bounds
        return v
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 添加图像视图
        let count = 4
        let rect = UIScreen.main.bounds
        for i in 0..<count {
            let imageName = "new_feature_\(i+1)"
            let imageView = UIImageView(image: UIImage(named: imageName))
            imageView.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(imageView)
        }
        
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.bounces = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        enterButton.isHidden = true
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
    }
  
    @IBAction func enterStatusClick() {
        removeFromSuperview()
    }
}


// MARK: - UIScrollViewDelegate
extension GYXNewFeatureView: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let count = scrollView.subviews.count
        if page == count {
            removeFromSuperview()
        }
        enterButton.isHidden = (page != count - 1)
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        enterButton.isHidden = true
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        pageControl.currentPage = page
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
}

